<template>
  <el-dialog
    v-model="dialogVisible"
    title="选择优惠券"
    width="600px"
    @close="handleClose"
  >
    <div class="coupon-select-content" v-loading="loading">
      <div class="order-amount">
        订单金额：<span class="amount">¥{{ orderAmount }}</span>
      </div>

      <div class="coupon-list">
        <el-empty v-if="!loading && availableCoupons.length === 0" description="暂无可用优惠券" />

        <div 
          v-for="coupon in availableCoupons" 
          :key="coupon.userCouponId"
          class="coupon-item"
          :class="{ 'selected': selectedCouponId === coupon.userCouponId }"
          @click="selectCoupon(coupon)"
        >
          <div class="coupon-left">
            <div class="coupon-amount">
              <template v-if="coupon.couponType === '0'">
                <span class="amount-symbol">¥</span>
                <span class="amount-value">{{ coupon.discountAmount }}</span>
              </template>
              <template v-else-if="coupon.couponType === '1'">
                <span class="amount-value">{{ (coupon.discountRate * 10).toFixed(1) }}</span>
                <span class="amount-unit">折</span>
              </template>
              <template v-else>
                <span class="amount-text">免费</span>
              </template>
            </div>
            <div class="coupon-condition">
              满{{ coupon.minAmount }}可用
            </div>
          </div>

          <div class="coupon-right">
            <div class="coupon-info">
              <h4 class="coupon-name">{{ coupon.couponName }}</h4>
              <div class="coupon-meta">
                <el-tag :type="getCouponTypeTag(coupon.couponType)" size="small">
                  {{ getCouponTypeName(coupon.couponType) }}
                </el-tag>
                <span v-if="coupon.couponType === '1'" class="max-discount">
                  最高优惠¥{{ coupon.maxDiscountAmount }}
                </span>
              </div>
              <div class="coupon-expire">
                有效期至：{{ formatTime(coupon.expireTime) }}
              </div>
            </div>

            <div class="coupon-discount">
              <div class="discount-text">可优惠</div>
              <div class="discount-amount">¥{{ calculateCouponDiscount(coupon) }}</div>
            </div>
          </div>

          <div class="select-indicator">
            <el-icon v-if="selectedCouponId === coupon.userCouponId" class="check-icon">
              <Check />
            </el-icon>
          </div>
        </div>

        <!-- 不使用优惠券选项 -->
        <div 
          class="coupon-item no-coupon-option"
          :class="{ 'selected': selectedCouponId === null }"
          @click="selectCoupon(null)"
        >
          <div class="no-coupon-content">
            <span>不使用优惠券</span>
          </div>
          <div class="select-indicator">
            <el-icon v-if="selectedCouponId === null" class="check-icon">
              <Check />
            </el-icon>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { getMyAvailableCoupons } from '@/api/coupon'
import { Check } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  orderAmount: {
    type: Number,
    required: true
  }
})

const emit = defineEmits(['update:modelValue', 'select'])

const dialogVisible = ref(props.modelValue)
const loading = ref(false)
const availableCoupons = ref([])
const selectedCouponId = ref(null)

// 监听外部传入的值
watch(() => props.modelValue, (val) => {
  dialogVisible.value = val
  if (val) {
    loadAvailableCoupons()
  }
})

// 监听内部值变化，同步到外部
watch(dialogVisible, (val) => {
  emit('update:modelValue', val)
})

// 加载可用优惠券
const loadAvailableCoupons = async () => {
  loading.value = true
  try {
    const data = await getMyAvailableCoupons(props.orderAmount)
    availableCoupons.value = data || []
  } catch (error) {
    console.error('获取可用优惠券失败:', error)
  } finally {
    loading.value = false
  }
}

// 选择优惠券
const selectCoupon = (coupon) => {
  selectedCouponId.value = coupon?.userCouponId || null
}

// 确认选择
const handleConfirm = () => {
  const selectedCoupon = availableCoupons.value.find(c => c.userCouponId === selectedCouponId.value)
  emit('select', selectedCoupon || null)
  dialogVisible.value = false
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 计算优惠券优惠金额
const calculateCouponDiscount = (coupon) => {
  const orderAmount = props.orderAmount

  if (coupon.couponType === '0') {
    // 满减券
    const discount = orderAmount >= coupon.minAmount ? coupon.discountAmount : 0
    return discount.toFixed(2)
  } else if (coupon.couponType === '1') {
    // 折扣券
    const discount = orderAmount * (1 - coupon.discountRate)
    return Math.min(discount, coupon.maxDiscountAmount).toFixed(2)
  } else if (coupon.couponType === '2') {
    // 免费券
    return orderAmount.toFixed(2)
  }
  return '0.00'
}

// 获取优惠券类型名称
const getCouponTypeName = (type) => {
  const typeMap = {
    '0': '满减券',
    '1': '折扣券',
    '2': '免费券'
  }
  return typeMap[type] || '优惠券'
}

// 获取优惠券类型标签
const getCouponTypeTag = (type) => {
  const tagMap = {
    '0': 'danger',
    '1': 'warning',
    '2': 'success'
  }
  return tagMap[type] || 'info'
}

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format('YYYY-MM-DD')
}
</script>

<style scoped>
.coupon-select-content {
  max-height: 500px;
  overflow-y: auto;
}

.order-amount {
  font-size: 16px;
  margin-bottom: 20px;
  text-align: center;
  padding: 15px;
  background: #f9f9f9;
  border-radius: 8px;
}

.amount {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.coupon-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.coupon-item {
  display: flex;
  border: 2px solid #e8e8e8;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.coupon-item:hover {
  border-color: #409eff;
}

.coupon-item.selected {
  border-color: #409eff;
  background: #f0f9ff;
}

.coupon-left {
  width: 120px;
  background: linear-gradient(135deg, #ff6b6b 0%, #ff4d4f 100%);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px 10px;
}

.coupon-amount {
  display: flex;
  align-items: baseline;
  margin-bottom: 8px;
}

.amount-symbol {
  font-size: 16px;
  font-weight: bold;
}

.amount-value {
  font-size: 32px;
  font-weight: bold;
  line-height: 1;
}

.amount-unit {
  font-size: 16px;
  font-weight: bold;
  margin-left: 2px;
}

.amount-text {
  font-size: 24px;
  font-weight: bold;
}

.coupon-condition {
  font-size: 12px;
  opacity: 0.9;
}

.coupon-right {
  flex: 1;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.coupon-info {
  flex: 1;
}

.coupon-name {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0 0 8px 0;
}

.coupon-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 8px;
}

.max-discount {
  font-size: 12px;
  color: #999;
}

.coupon-expire {
  font-size: 12px;
  color: #666;
}

.coupon-discount {
  text-align: center;
  margin-right: 15px;
}

.discount-text {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.discount-amount {
  font-size: 18px;
  font-weight: bold;
  color: #ff4d4f;
}

.select-indicator {
  width: 30px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.check-icon {
  font-size: 20px;
  color: #409eff;
}

.no-coupon-option {
  border-style: dashed;
}

.no-coupon-content {
  flex: 1;
  text-align: center;
  padding: 20px;
  color: #666;
  font-size: 16px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
